package com.ruoyi.web.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.novel.domain.*;
import com.ruoyi.novel.service.*;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户相关接口
 */

@RestController
@RequestMapping("/app/user")
public class AppUserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IVideoService videoService;

    @Autowired
    private IFriendsService friendsService;

    @Autowired
    private IRecordsService recordsService;

    @Autowired
    private ICommunityService communityService;

    @Autowired
    private INovelService novelService;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private ISearchService searchService;

    @Autowired
    private TokenService tokenService;

    /**
     * 绑定邀请用户
     * @param code
     * @return
     */
    @GetMapping("/bindingUser")
    public AjaxResult bindingUser(String code){
        Long userId = SecurityUtils.getUserId();
        List<User> userList = userService.list(new QueryWrapper<User>().like("phone", code));
        if(!userList.isEmpty()){
            User user = userList.get(0);
            List<String> list = new ArrayList<>();
            list.addAll(Arrays.asList(user.getAncestors().split(",")));
            String id = String.valueOf(user.getId());
            if(list.isEmpty() || list == null){
                list = new ArrayList<>();
                list.add("0");
                list.add(id);
            }else {
                list.add(id);
            }
            String ancestors = String.join(",", list);
            boolean update = userService.update(new UpdateWrapper<User>().eq("id", userId).eq("referrer", 0).set("referrer", user.getId()).set("ancestors", ancestors));
            if(update){
                return AjaxResult.success(update);
            }else {
                return AjaxResult.error("用户已被邀请");
            }
        }else {
            return AjaxResult.error("邀请码错误");
        }
    }

    /**
     * 修改手机号
     * @param phone
     * @return
     */
    @Transactional
    @GetMapping("/updatePhone")
    public AjaxResult updatePhone(String phone){
        Long userId = SecurityUtils.getUserId();

        SysUser user = new SysUser();
        user.setUserId(userId);
        user.setPhonenumber(phone);
        boolean b = sysUserService.checkPhoneUnique(user);
        if(!b){
            return AjaxResult.error("该手机号已注册");
        }else {
            user.setUserName(phone);
            sysUserService.updateUserName(user);
            userService.update(new UpdateWrapper<User>().eq("id", userId).set("phone", phone));
        }
        return AjaxResult.success("修改成功");
    }

    /**
     * 修改用户密码
     * @param phone 原密码
     * @param password 新密码
     * @param code 验证码
     * @return
     */
    @PostMapping("/updatePwdByPhone")
    public AjaxResult updatePwdByPhone(@RequestBody Map<String, String> params)
    {
        String phone = params.get("phone");
        String newPassword = params.get("password");
        String code = params.get("code");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userName = phone;
        String password = loginUser.getPassword();
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (sysUserService.resetUserPwd(userName, newPassword) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 修改用户密码
     * @param oldPassword 原密码
     * @param newPassword 新密码
     * @return
     */
    @PostMapping("/updatePwd")
    public AjaxResult updatePwd(@RequestBody Map<String, String> params)
    {
        String oldPassword = params.get("oldPassword");
        String newPassword = params.get("newPassword");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        newPassword = SecurityUtils.encryptPassword(newPassword);
        if (sysUserService.resetUserPwd(userName, newPassword) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(newPassword);
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 获取搜索记录
     * @param mode 模式 0视频 1社区 2小说 3漫画
     * @return
     */
    @GetMapping("/getSearchList")
    public AjaxResult getSearchList(Integer mode){
        AjaxResult result = AjaxResult.success();
        List<Search> list = searchService.list(new QueryWrapper<Search>().eq("mode", mode).eq("user_id",0).eq("state", 0));
        result.put("tuiList",list);
        List<Search> user = searchService.list(new QueryWrapper<Search>().eq("mode", mode).gt("user_id",0).eq("state", 0));
        result.put("userList",list);
        return result;
    }

    /**
     * 获取视频详情
     * @param videoId
     * @return
     */
    @GetMapping("/getVideoById")
    public AjaxResult getVideoById(Integer videoId){
        AjaxResult result = AjaxResult.success();
        long count = recordsService.count(new QueryWrapper<Records>().eq("video_id", videoId).eq("type", 0));
        result.put("browseNum",count);
        //添加浏览记录
        Records records = new Records();
        records.setUserId(Math.toIntExact(SecurityUtils.getUserId()));
        records.setVideoId(videoId);
        records.setType(0);
        records.setCreateTime(new Date());
        recordsService.save(records);
        Video video = videoService.getById(videoId);
        result.put("data",video);
        return result;
    }

    /**
     * 获取交友信息列表
     * @param friendsId
     * @return
     */
    @GetMapping("/getFriendsById")
    public AjaxResult getFriendsById(Integer friendsId){
        AjaxResult result = AjaxResult.success();
        //添加浏览记录
        Records records = new Records();
        records.setUserId(Math.toIntExact(SecurityUtils.getUserId()));
        records.setFriendsId(friendsId);
        records.setType(0);
        records.setCreateTime(new Date());
        recordsService.save(records);
        Friends friends = friendsService.getById(friendsId);
        result.put("data",friends);
        return result;
    }

    /**
     * 获取用户已购买的交友信息订单
     * @param friendsId
     * @return
     */
    @GetMapping("/getFriendsOrderById")
    public AjaxResult getFriendsOrderById(Integer friendsId){
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state",10).eq("user_id", SecurityUtils.getUserId()).eq("friends_id", friendsId);
        List<Order> orderList = orderService.list(queryWrapper);
        return AjaxResult.success(orderList);
    }

    /**
     * 获取社区文章详情
     * @param communityId
     * @return
     */
    @GetMapping("/getCommunityById")
    public AjaxResult getCommunityById(Integer communityId){
        AjaxResult result = AjaxResult.success();
        //添加浏览记录
        Records records = new Records();
        records.setUserId(Math.toIntExact(SecurityUtils.getUserId()));
        records.setCommunityId(communityId);
        records.setType(0);
        records.setCreateTime(new Date());
        recordsService.save(records);
        List<Community> communityList = communityService.getCommunityById(new QueryWrapper<Community>().eq("c.id", communityId), Math.toIntExact(SecurityUtils.getUserIdNotLogin()));
        if(communityList.size()>0){
            result.put("data",communityList.get(0));
            //获取买没买这个文章
            long count = orderService.count(new QueryWrapper<Order>().eq("community_id", communityId).gt("state", 0));
            result.put("isPay",count);
            return result;
        }else {
            return AjaxResult.error("信息有误");
        }
    }

    /**
     * 获取小说详情
     * @param novelId
     * @return
     */
    @GetMapping("/getNovelById")
    public AjaxResult getNovelById(Integer novelId){
        AjaxResult result = AjaxResult.success();
        //添加浏览记录
        Records records = new Records();
        records.setUserId(Math.toIntExact(SecurityUtils.getUserId()));
        records.setNovelId(novelId);
        records.setType(0);
        records.setCreateTime(new Date());
        recordsService.save(records);
        Novel novel = novelService.getById(novelId);
        result.put("data",novel);
        long count = recordsService.count(new QueryWrapper<Records>().eq("user_id", SecurityUtils.getUserId()).eq("novel_id", novelId).eq("type", 10));
        result.put("isShangjia",count);// >0 在我的书架
        QueryWrapper<Novel> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id", "title", "integral").eq("p_id",novelId);
        List<Novel> novelList = novelService.list(queryWrapper);

//        if(novelList.size() > 0){
//            List<Integer> ids = novelList.stream().map(Novel::getId).collect(Collectors.toList());
//            QueryWrapper<Novel> wrapper = new QueryWrapper<>();
//            wrapper.select("id", "title", "integral").in("p_id",ids);
//            novelList.addAll(novelService.list(wrapper));
//        }
        result.put("novelList",novelList);
        return result;
    }

    /**
     * 加入书架
     * @param novelId
     * @return
     */
    @PostMapping("/addBookRack")
    public AjaxResult addBookRack(Integer novelId){
        //添加浏览记录
        Records records = new Records();
        records.setUserId(Math.toIntExact(SecurityUtils.getUserId()));
        records.setNovelId(novelId);
        records.setType(0);
        records.setState(10);
        records.setCreateTime(new Date());
        return AjaxResult.success(recordsService.save(records));
    }

    /**
     * 获取我相关的视频
     * @param type 类型 0浏览 1收藏 2关注 10加入书架
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getUserVideoList")
    public AjaxResult getUserVideoList(Integer type, Integer pageNo, Integer pageSize){
        IPage<Video> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("r.user_id", SecurityUtils.getUserId()).gt("r.video_id", 0).eq("r.type", type);
        queryWrapper.groupBy("v.id").orderByDesc("r.id");
        IPage<Video> videoIPage = videoService.getUserVideoList(page, queryWrapper);
        return AjaxResult.success(videoIPage);
    }

    /**
     * 获取我购买的视频
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getOrderVideoList")
    public AjaxResult getOrderVideoList(Integer pageNo, Integer pageSize){
        IPage<Video> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("r.user_id", SecurityUtils.getUserId()).gt("r.video_id", 0).eq("r.state", 10);
        queryWrapper.groupBy("v.id").orderByDesc("r.id");
        IPage<Video> videoIPage = videoService.getOrderVideoList(page, queryWrapper);
        return AjaxResult.success(videoIPage);
    }

    /**
     * 获取我相关的社区文章
     * @param type 类型 0浏览 1收藏 2关注 10加入书架
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getUserCommunityList")
    public AjaxResult getUserCommunityList(Integer type, Integer pageNo, Integer pageSize){
        IPage<Community> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Community> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("r.user_id", SecurityUtils.getUserId()).gt("r.community_id", 0).eq("r.type", type);
        queryWrapper.groupBy("c.id").orderByDesc("r.id");
        IPage<Community> communityIPage = communityService.getUserCommunityList(page, queryWrapper);
        return AjaxResult.success(communityIPage);
    }

    /**
     * 获取我购买的文章
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getOrderCommunityList")
    public AjaxResult getOrderCommunityList(Integer pageNo, Integer pageSize){
        IPage<Community> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Community> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("r.user_id", SecurityUtils.getUserId()).gt("r.community_id", 0).eq("r.state", 10);
        queryWrapper.groupBy("c.id").orderByDesc("r.id");
        IPage<Community> communityIPage = communityService.getOrderCommunityList(page, queryWrapper);
        return AjaxResult.success(communityIPage);
    }

    /**
     * 获取我相关的交友信息
     * @param type 类型 0浏览 1收藏 2关注 10加入书架
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getUserFriendsList")
    public AjaxResult getUserFriendsList(Integer type, Integer pageNo, Integer pageSize){
        IPage<Friends> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Friends> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("r.user_id", SecurityUtils.getUserId()).gt("r.friends_id", 0).eq("r.type", type);
        queryWrapper.groupBy("f.id").orderByDesc("r.id");
        IPage<Friends> friendsIPage = friendsService.getUserFriendsList(page, queryWrapper);
        return AjaxResult.success(friendsIPage);
    }

    /**
     * 获取我购买的交友信息
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getOrderFriendsList")
    public AjaxResult getOrderFriendsList(Integer pageNo, Integer pageSize){
        IPage<Friends> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Friends> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("r.user_id", SecurityUtils.getUserId()).gt("r.friends_id", 0).eq("r.state", 10);
        queryWrapper.groupBy("f.id").orderByDesc("r.id");
        IPage<Friends> friendsIPage = friendsService.getOrderFriendsList(page, queryWrapper);
        return AjaxResult.success(friendsIPage);
    }

    /**
     * 获取我相关的小说/漫画
     * @param type 类型 0浏览 1收藏 2关注 10加入书架
     * @param mode 模式 0小说 1漫画
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getUserNovelList")
    public AjaxResult getUserNovelList(Integer type, Integer mode, Integer pageNo, Integer pageSize){
        IPage<Novel> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Novel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("r.user_id", SecurityUtils.getUserId()).gt("r.novel_id", 0).eq("r.type", type).eq("n.mode", mode);
        queryWrapper.groupBy("n.id").orderByDesc("r.id");
        IPage<Novel> friendsIPage = novelService.getUserNovelList(page, queryWrapper);
        return AjaxResult.success(friendsIPage);
    }

    /**
     * 获取我购买的小说/漫画
     * @param mode 模式 0小说 1漫画
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/getOrderNovelList")
    public AjaxResult getOrderNovelList(Integer mode, Integer pageNo, Integer pageSize){
        IPage<Novel> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Novel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("r.user_id", SecurityUtils.getUserId()).gt("r.novel_id", 0).eq("r.state", 10).eq("n.mode", mode);
        queryWrapper.groupBy("n.id").orderByDesc("r.id");
        IPage<Novel> friendsIPage = novelService.getOrderNovelList(page, queryWrapper);
        return AjaxResult.success(friendsIPage);
    }

}
